package com.ocean.linkedlist;

/**
 * https://leetcode.cn/problems/linked-list-cycle/
 */
public class LinkedListCycle3 {
    public static void main(String[] args) {

        ListNode e5 = new ListNode(5, null);
        ListNode e4 = new ListNode(4, e5);
        ListNode e3 = new ListNode(3, e4);
        ListNode e2 = new ListNode(2, e3);
        ListNode e1 = new ListNode(1, e2);
//        e5.next = e1;
        boolean b = new LinkedListCycle3().hasCycle(e1);
        System.out.println(b);
    }


    /**
     * 检测链表是否有环
     *
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        // 快指针赶上慢指针 则一定存在环
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null) {
            ListNode next = fast.next;
            if (next == slow) {
                return true;
            }
            fast = next.next;
            slow = slow.next;
        }
        return false;
    }
}
